import base64
import random
import logging

# Create your views here.


from django.views import View
from django import http
from django_redis import get_redis_connection

# from celery_tasks.sms.yuntongxun.ccp_sms import CCP
from meiduo_mall.utils.response_code import RETCODE
from verifications.libs.captcha.captcha import captcha
from celery_tasks.sms.tasks import send_sms_code
from . import constants

logger = logging.getLogger('django')


class SMSCodeView(View):

    def get(self, requset, mobile):

        uuid = requset.GET.get('uuid')
        image_code_client = requset.GET.get('image_code')

        if not all([uuid, image_code_client]):
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码错误'})

        redis_conn = get_redis_connection('verify_code')

        # 判断用户是否频繁发送短信验证码
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})

        # 'img_%s' % uuid
        image_code_server = redis_conn.get('img_%s' % uuid)

        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码失效'})

        redis_conn.delete('mobile_%s' % mobile)

        image_code_server = image_code_server.decode()

        if image_code_server.lower() != image_code_client.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码过期'})

        sms_code = ''.join(str(random.randint(0, 9)) for i in range(6))

        logger.info('{mobile} => {sms_code}'.format(mobile=mobile, sms_code=sms_code))
        # 创建Redis管道
        p1 = redis_conn.pipeline()

        # 为管道添加指令,最多三个.
        p1.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        p1.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, constants.SEND_SMS_TEMPLATE_ID)
        # 执行管道
        p1.execute()

        # 保存短信验证码
        # redis_conn.setex('sms_%s'%mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 发送短信验证码 300 / 60 = 5.0, 300 // 60 = 5
        # redis_conn.setex('send_flag_%s' %mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        send_sms_code.delay(mobile, sms_code)
        # CCP().send_template_sms(mobile, [sms_code, constants.IMAGE_CODE_REDIS_EXPIRES // 60],
        #                         constants.SEND_SMS_TEMPLATE_ID)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功'})


class ImageCodeView(View):
    def get(self, requset, uuid):
        # 将captcha.generate_captcha()生成的图片经行拆包，text是值，image是图片
        text, image = captcha.generate_captcha()

        # 连接CACHES中定义后的redis数据库
        redis_conn = get_redis_connection('verify_code')

        # 设置redis中图片的key，延时，以及值
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 将图片信息以Data URI 的方式发送给前端
        image = base64.b64encode(image)
        return http.HttpResponse(image, content_type='image/jpg')
